const app = getApp()

Page({
  data: {
    userInfo: null,
    articles: [],
    stats: {
      articleCount: 0,
      examCount: 0,
      certificateCount: 0,
      rank: 0
    }
  },

  onLoad() {
    this.checkLogin()
    this.loadArticles()
  },

  onShow() {
    if (this.data.userInfo) {
      this.loadUserStats()
    }
  },

  // 检查登录状态
  checkLogin() {
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo) {
      this.setData({
        userInfo: userInfo
      })
      this.loadUserStats()
    }
  },

  // 加载推荐文章
  async loadArticles() {
    try {
      wx.showLoading({
        title: '加载中...'
      })

      const res = await app.request({
        url: '/articles',
        method: 'GET',
        data: {
          page: 1,
          per_page: 5
        }
      })

      if (res.success) {
        this.setData({
          articles: res.data.items || []
        })
      }
    } catch (error) {
      console.error('加载文章失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 加载用户统计
  async loadUserStats() {
    try {
      // 获取用户统计数据
      const [userStatsRes, rankRes] = await Promise.all([
        app.request({
          url: '/users/stats',
          method: 'GET'
        }),
        app.request({
          url: '/leaderboards/my-rank',
          method: 'GET'
        })
      ])

      let stats = {
        articleCount: 0,
        examCount: 0,
        certificateCount: 0,
        rank: 0
      }

      if (userStatsRes.success) {
        const userData = userStatsRes.data
        stats.examCount = userData.total_exams || 0
        stats.certificateCount = userData.certificate_count || 0
      }

      if (rankRes.success) {
        const rankData = rankRes.data
        stats.rank = rankData.rank_position || 0
      }

      this.setData({ stats })
    } catch (error) {
      console.error('加载用户统计失败:', error)
    }
  },

  // 跳转到文章列表
  goToArticles() {
    wx.navigateTo({
      url: '/pages/articles/articles'
    })
  },

  // 跳转到考试列表
  goToExams() {
    wx.navigateTo({
      url: '/pages/exams/exams'
    })
  },

  // 跳转到证书列表
  goToCertificates() {
    wx.navigateTo({
      url: '/pages/certificates/certificates'
    })
  },

  // 跳转到排行榜
  goToLeaderboard() {
    wx.navigateTo({
      url: '/pages/leaderboard/leaderboard'
    })
  },

  // 跳转到文章详情
  goToArticle(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/article/article?id=${id}`
    })
  }
}) 